package org.cypress.rtpack.service;

import org.cypress.rtpack.VO.SoeIp;
import org.cypress.rtpack.VO.SoeLastTime;
import org.cypress.rtpack.VO.SoeLs;
import org.cypress.rtpack.entity.SoeSysname;
import org.cypress.rtpack.utils.Dbsvr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.net.*;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class SOEProcessorService {
    private static final Logger logger = LoggerFactory.getLogger(SOEProcessorService.class);

    // 存储当前运行的 sysnum 及其线程状态（true=运行中）
    private final ConcurrentHashMap<Integer, AtomicBoolean> runningThreads = new ConcurrentHashMap<>();

    @Autowired
    private ISoeSysnameService soeSysnameService;



    @Value("${usc8000.server.port:8089}")
    private int serverPort;

    @Value("${usc8000.server.timeout:5000}")
    private int socketTimeout;

    // 从配置文件中读取间隔时间，默认5秒
    @Value("${usc8000.process.interval:5000}")
    private long processInterval;
    private final ExecutorService executor;

    //@Autowired
    public SOEProcessorService(ExecutorService alarmExecutor) {
        this.executor = alarmExecutor;
    }

    /**
     * 应用启动后自动启动线程       @PostConstruct可能在主流程跑完前自行启动
     */
    public void startProcessing() {
        executor.submit(() -> {
            logger.info("SOE采集线程启动，处理间隔: {}ms", processInterval);
            while (!Thread.currentThread().isInterrupted()) {
                List<SoeSysname> sysnameList = soeSysnameService.getAll();
                sysnameList.forEach(item -> {   //查询系统的循环
                    int sysnum = item.getId();
                    boolean sysEnb = item.isEnabled();
                    // 只处理 enabled=true 的系统
                    if (sysEnb) {
                        logger.info("检查系统: ID={}, Enabled={}", sysnum, sysEnb);

                        // 如果 sysnum 不在 runningThreads 中，或线程已终止，则启动新线程
                        runningThreads.compute(sysnum, (key, isRunning) -> {
                            if (isRunning == null || !isRunning.get()) {
                                logger.info("启动子线程处理系统: ID={}", sysnum);
                                executor.submit(() -> processSysnumTasks(sysnum));
                                return new AtomicBoolean(true); // 标记为运行中
                            }
                            return isRunning; // 线程已在运行，无需处理
                        });
                    }
                });

                try {
                    Thread.sleep(processInterval);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logger.info("SOE采集线程被中断");
                } catch (Exception e) {
                    logger.error("SOE采集发生异常", e);
                }
            }
        });
    }

    /**
     * 处理单个 sysnum 的任务（子线程逻辑）
     */
    private void processSysnumTasks(int sysnum) {
        try {
            logger.info("子线程启动，处理系统: ID={}", sysnum);
            while (!Thread.currentThread().isInterrupted()) {
                SoeSysname soeSysname = soeSysnameService.getById(sysnum);
                if (soeSysname == null){
                    Thread.sleep(processInterval);
                    continue;
                }
                if (soeSysname.isEnabled()){
                    // 实际业务逻辑：查询 IP 列表并处理
                    List<SoeIp> ipList = Dbsvr.getList(String.format("soe_s%spt", sysnum), "soe_ip", SoeIp.class);
                    AtomicBoolean readSuc = new AtomicBoolean(false);
                    ipList.forEach(item -> {
                        logger.info("SOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOE{},{}", readSuc.get(), item.isEnabled());
                        if ((!readSuc.get()) && item.isEnabled()){
                            logger.info("SOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOESOE");
                            logger.info("系统{}尝试连接{}", sysnum, item.getIp());
                            boolean res = processSOEs(sysnum,item.getIp());
                            if(res){
                                readSuc.set(true);
                            }
                        }
                    });
                }
                Thread.sleep(processInterval);
            }
        } catch (InterruptedException e) {
            logger.info("系统 {} 的处理线程被中断", sysnum);
        } finally {
            // 线程结束时，从 runningThreads 中移除
            runningThreads.remove(sysnum);
            logger.info("系统 {} 的处理线程已终止", sysnum);
        }
    }

    /**
     * 实际的SOE采集逻辑
     * 连接服务器，发送请求，读取数据，然后关闭连接
     */
    private boolean processSOEs(int sysnum,String serverHost) {
        Socket socket = null;
        OutputStream out = null;
        InputStream in = null;
        String totalRep = "";
        boolean ret = false;
        try {
            logger.info("SOE开始连接控制器11");
            // 创建Socket连接
            socket = new Socket(serverHost, serverPort);
            socket.setSoTimeout(socketTimeout);
            logger.debug("SOE成功连接到服务器 {}:{}", serverHost, serverPort);

            // 获取输出流发送字节数组
            out = socket.getOutputStream();
            //85 170 235 3 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0
            SoeLastTime soeLastTime = Dbsvr.getEntity(String.format("soe_s%spt",sysnum),"last_time",SoeLastTime.class,0,"\"index\"");
            logger.info("获取时间戳:{}",soeLastTime);
            byte[] btAr1= ByteBuffer.allocate(4).putInt(soeLastTime.getUnixTime1()).array();
            logger.info("获取时间戳:{}-{}-{}-{}",btAr1[3],btAr1[2],btAr1[1],btAr1[0]);
            byte[] btAr2= ByteBuffer.allocate(4).putInt(soeLastTime.getUnixTime2()).array();
            logger.info("获取时间戳:{}-{}-{}-{}",btAr2[3],btAr2[2],btAr2[1],btAr2[0]);

            /*
            int microseconds = soeLastTime.getUnixTime2();
            int nanoTruncated = (int)((long)microseconds * 1000);
            byte[] btAr2 = ByteBuffer.allocate(4).putInt(nanoTruncated).array();
            */
            // 向设备发送请求报文
            byte[] requestData = {85, (byte) 170,(byte) 235,3,0,0,0,0,0,0,0,0,8,0,0,0,btAr1[3],btAr1[2],btAr1[1],btAr1[0],btAr2[3],btAr2[2],btAr2[1],btAr2[0]}; // 要发送的字节数组
            out.write(requestData);
            out.flush();
            logger.debug("已发送SOE Request到控制器");

            // 获取输入流读取响应
            in = socket.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            boolean receivedHead = false;
            int expectSize = 2049;
            int totalBytes = 0;  //累计接收了多少数据
            int bytesRead;


            while ((bytesRead = in.read(buffer)) != -1)
            {
                logger.info("获取字节数:{}",bytesRead);
                if (bytesRead > 0)
                {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;  //累计接收了多少数据
                    if(receivedHead)
                    {
                        logger.info("累计收到{}字节",totalBytes);
                        if (totalBytes >= expectSize)
                        {
                            logger.info("接收完毕");
                            break;
                        }
                    }
                    else
                    {
                        if(totalBytes >= 16){  //累计接收了多少数据 >= 16字节，则认为收到了头
                            logger.info("头状态头状态头状态:{}",receivedHead);
                            boolean jdIsHead = true;
                            byte[] responseBytes = byteArrayOutputStream.toByteArray();
                            if((responseBytes[0] != -86) || (responseBytes[1] != 85) || (responseBytes[2] != -21) || (responseBytes[3] != 3))
                            {
                                jdIsHead = false;
                                logger.info("reply with invalid head &{}&{}&{}&{}",responseBytes[0],responseBytes[1],responseBytes[2],responseBytes[3]);
                            }
                            if(jdIsHead) 
                            {
                                byte[] bytes = {responseBytes[15], responseBytes[14], responseBytes[13], responseBytes[12]};
                                expectSize = ByteBuffer.wrap(bytes).getInt() + 16;    //报文里字节为接下来有效数据字节。用总字节数比较，还需要加上head的16字节
                                logger.info("expectSize={}",expectSize);
                                //expectSize = 18;  //调试期间，避免一致等待
                                receivedHead = true;
                                logger.info("头状态头状态头状态:{}",receivedHead);
                            }
                            logger.info("{}哈哈{}",totalBytes,expectSize);
                            if(totalBytes >= expectSize) 
                            {
                                logger.info("接收完毕A");
                                break;
                            }
                        }
                    }
                }
            }
            byte[] responseBytes = byteArrayOutputStream.toByteArray();
            logger.info("从控制器收到的响应字节数: {}", responseBytes.length);
            logger.info("控制器响应数据(十六进制): {}", bytesToHex(responseBytes));

            if(receivedHead)
            {
                ret = true;
                logger.info("尝试解析");
//                int offset = 16;
//                if (offset + 2 <= totalBytes)
//                {
//                    byte[] bytes2A = { responseBytes[17],responseBytes[16] };  //后面数据数量字节
//                    short itemCount = ByteBuffer.wrap(bytes2A).getShort();
//                    offset += 2;
//                    logger.info("itemCount={}",itemCount);
//                    SoeLastTime soeLastTime1 = soeLastTime;
//                    for(int i = 0; i < itemCount; i++)
//                    {
//                        if (offset + 18 < expectSize) {   //一个事件是19字节，角标offset -- offset+18表示
//                            byte[] bytes4A = {responseBytes[offset + 3], responseBytes[offset + 2], responseBytes[offset + 1], responseBytes[offset]};
//                            int mySeconds = ByteBuffer.wrap(bytes4A).getInt();
//                            offset += 4;
//                            //纳秒
//                            byte[] bytes4B = {responseBytes[offset + 3], responseBytes[offset + 2], responseBytes[offset + 1], responseBytes[offset]};
//                            int myNanos2 = ByteBuffer.wrap(bytes4B).getInt();
//                            //int myNanos2 = myNanos1 * 1000;    // 毫秒转成纳秒级
//                            offset += 4;
//                            Instant instant = Instant.ofEpochSecond(mySeconds, myNanos2);
//                            //logger.info("mySeconds={}", mySeconds);
//                            //logger.info("myNanos={}", myNanos);
//                            //logger.info("instant={}", instant);
//                            short nameLen = (short) Byte.toUnsignedInt(responseBytes[offset++]);  // 名称长度
//                            //logger.info("nameLen={}", nameLen);
//                            byte[] bytes2B = {responseBytes[offset + 1], responseBytes[offset]};
//                            offset += 2;
//                            short typeV = ByteBuffer.wrap(bytes2B).getShort();  //事件类型
//                            //logger.info("typeV={}", typeV);
//                            short valueLen = (short) Byte.toUnsignedInt(responseBytes[offset++]);
//                            //logger.info("valueLen={}", valueLen);
//                            int eventV = Byte.toUnsignedInt(responseBytes[offset++]);
//                            //logger.info("eventV={}", eventV);
//                            short nameV = (short) Byte.toUnsignedInt(responseBytes[offset++]);
//                            //logger.info("nameV={}", nameV);
//                            String channelName = Short.toString(nameV);   //位号
//                            short pointIndex = (short) Byte.toUnsignedInt(responseBytes[offset++]);
//                            //logger.info("pointIndex={}", pointIndex);
//                            switch (typeV) {
//                                case 0:
//                                    break;
//                                case 1:
//                                    break;
//                                case 2:
//                                    break;
//                                case 3:
//                                    break;
//                                case 4:
//                                    break;
//                                case 5:
//                                    channelName += "_0";
//                                    break;
//                                case 6:
//                                    channelName += "_1";
//                                    break;
//                                case 7:
//                                    channelName += "_2";
//                                    break;
//                                case 8:
//                                    channelName += "_3";
//                                    break;
//                                default:
//                                    break;
//                            }
//                            channelName += "_" + pointIndex;
//                            //logger.info("nameS={}", nameS);
//                            byte[] bytes4C = {responseBytes[offset + 3], responseBytes[offset + 2], responseBytes[offset + 1], responseBytes[offset]};
//                            offset += 4;
//                            float val = ByteBuffer.wrap(bytes4C).getFloat();
//                            //logger.info("value={}", value);
//                            logger.info("-->{}\t{}\t{}\t{}",instant,channelName,eventV,val);
//                            SoeLs soeLs = SoeLs.builder()
//                                    .unixTime1(mySeconds)
//                                    .unixTime2(myNanos2)
//                                    .channelName(channelName)
//                                    .eventV(eventV)
//                                    .val(val)
//                                    .build();
//                            logger.info("ooo-->{}",soeLs);
//                            if (!Dbsvr.isEntityExists(String.format("soe_s%spt",sysnum),"soe_ls",soeLs)){
//                                logger.info("实体不存在，准备添加");
//                                if(Dbsvr.insertEntity(String.format("soe_s%spt",sysnum),"soe_ls",soeLs)){
//                                    logger.info("实体添加成功");
//                                }
//                            }
//
//                            SoeLastTime soeLastTimeNew = SoeLastTime.builder().index(0).unixTime1(mySeconds).unixTime2(myNanos2).build();
//                            if(soeLastTimeNew.isNewer(soeLastTime1)){
//                                soeLastTime1 = soeLastTimeNew;
//                            }
//                        }
//                    }
//                    if(soeLastTime1.isNewer(soeLastTime)){
//                        Dbsvr.updateEntity(String.format("soe_s%spt",sysnum),"last_time","\"index\"",soeLastTime1);
//                    }
//                }

                // 新SOE报文解析逻辑
                logger.info("开始解析新SOE报文格式");
                int newOffset = 16; // 跳过16字节头部
                if (newOffset + 2 <= totalBytes)
                {
                    byte[] newBytes2A = { responseBytes[17], responseBytes[16] }; //后面数据总字节数据
                    short newItemCount = ByteBuffer.wrap(newBytes2A).getShort();
                    newOffset += 2;
                    logger.info("新SOE事件数量: {}", newItemCount);
                    SoeLastTime newSoeLastTime1 = soeLastTime;
                    for(int i = 0; i < newItemCount; i++)
                    {
                        // 解析数据长度（前2字节）
                        //byte[] dataLengthBytes = { responseBytes[newOffset + 1], responseBytes[newOffset] };
                        int dataLength = Byte.toUnsignedInt(responseBytes[newOffset++]);
                        //newOffset += 2;
                        newOffset++;
                        logger.info("新SOE数据长度: {} 字节", dataLength);
                        // 根据报文格式，解析单个SOE事件
                        if (newOffset + 8 <= totalBytes) { // 至少需要8字节（utc_time）
                            // 1. 解析UTC时间戳（8字节：4字节秒 + 4字节微秒）
                            byte[] utcSecondsBytes = {responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                    responseBytes[newOffset + 1], responseBytes[newOffset]};
                            int utcSeconds = ByteBuffer.wrap(utcSecondsBytes).getInt();
                            newOffset += 4;

                            byte[] utcMicrosecondsBytes = {responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                    responseBytes[newOffset + 1], responseBytes[newOffset]};
                            int utcMicroseconds = ByteBuffer.wrap(utcMicrosecondsBytes).getInt();
                            newOffset += 4;

                            // 转换微秒为纳秒
                            //long utcNanos = utcMicroseconds * 1000L;
                            Instant newInstant = Instant.ofEpochSecond(utcSeconds, utcMicroseconds);

                            // 2. 解析名称长度（1字节）
                            int nameLen = Byte.toUnsignedInt(responseBytes[newOffset++]);
                            logger.info("解析名称长度: {}", nameLen);
                            // 3. 解析名称字符串（变长，UTF-8编码，以0x00终止）
                            String channelName = "";
                            if (nameLen > 0) {
                                byte[] nameBytes = new byte[nameLen];
                                System.arraycopy(responseBytes, newOffset, nameBytes, 0, nameLen);
                                newOffset += nameLen;

                                // 查找字符串终止符0x00
                                int nullIndex = -1;
                                for (int j = 0; j < nameLen; j++) {
                                    if (nameBytes[j] == 0x00) {
                                        nullIndex = j;
                                        break;
                                    }
                                }

                                if (nullIndex > 0) {
                                    byte[] actualNameBytes = new byte[nullIndex];
                                    System.arraycopy(nameBytes, 0, actualNameBytes, 0, nullIndex);
                                    channelName = new String(actualNameBytes, java.nio.charset.StandardCharsets.UTF_8);
                                } else if (nullIndex == -1) {
                                    channelName = new String(nameBytes, java.nio.charset.StandardCharsets.UTF_8);    //直接将 UTF_8的编码转换成字符串
                                }
                            }

                            // 4. 解析事件类型（1字节）
                            int eventType = Byte.toUnsignedInt(responseBytes[newOffset++]);
                            logger.info("解析事件类型: {}", eventType);
                            // 5. 解析值类型标识（1字节）
                            int vaType = Byte.toUnsignedInt(responseBytes[newOffset++]);
                            logger.info("解析值类型标识: {}", vaType);
                            // 6. 根据值类型解析实际值（变长）
                            Object value = null;
                            if (newOffset < totalBytes) {
                                switch (vaType) {
                                    case 0: // char (1字节)
                                        if (newOffset >= totalBytes) {
                                            logger.error("VaType=0：数据不足（需1字节）");
                                            break;
                                        }
                                        value = (char) responseBytes[newOffset++];
                                        logger.info("解析char值: {}", value);
                                        break;
                                    case 1: // unsigned char (1字节)
                                        if (newOffset >= totalBytes) {
                                            logger.error("VaType=1：数据不足（需1字节）");
                                            break;
                                        }
                                        value = Byte.toUnsignedInt(responseBytes[newOffset++]);
                                        break;
                                    case 2: // short (2字节)
                                        if (newOffset + 1 >= totalBytes) {
                                            logger.error("VaType=2：数据不足（需2字节）");
                                            break;
                                        }
                                        byte[] shortBytes = {responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(shortBytes).getShort();
                                        newOffset += 2;
                                        break;
                                    case 3: // unsigned short (2字节)
                                        if (newOffset + 1 >= totalBytes) {
                                            logger.error("VaType=3：数据不足（需2字节）");
                                            break;
                                        }
                                        byte[] ushortBytes = {responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(ushortBytes).getShort() & 0xFFFF; // 转换为无符号short
                                        newOffset += 2;
                                        break;
                                    case 4: // long (4字节，对应Java int)
                                        if (newOffset + 3 >= totalBytes) {
                                            logger.error("VaType=4：数据不足（需4字节）");
                                            break;
                                        }
                                        byte[] intBytes = {responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(intBytes).getInt();
                                        newOffset += 4;
                                        break;
                                    case 5: // unsigned long (4字节，对应Java long的低32位)
                                        if (newOffset + 3 >= totalBytes) {
                                            logger.error("VaType=5：数据不足（需4字节）");
                                            break;
                                        }
                                        byte[] uintBytes = {responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(uintBytes).getInt() & 0xFFFFFFFFL; // 转换为无符号int
                                        newOffset += 4;
                                        break;
                                    case 6: // float (4字节)
                                        if (newOffset + 3 >= totalBytes) {
                                            logger.error("VaType=6：数据不足（需4字节）");
                                            break;
                                        }
                                        byte[] floatBytes = {responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(floatBytes).getFloat();
                                        newOffset += 4;
                                        break;
                                    case 7: // long long (8字节，对应Java long)
                                        if (newOffset + 7 >= totalBytes) {
                                            logger.error("VaType=7：数据不足（需8字节）");
                                            break;
                                        }
                                        byte[] longBytes = {responseBytes[newOffset + 7], responseBytes[newOffset + 6],
                                                responseBytes[newOffset + 5], responseBytes[newOffset + 4],
                                                responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(longBytes).getLong();
                                        newOffset += 8;
                                        break;
                                    case 8: // unsigned long long (8字节，对应Java long)
                                        if (newOffset + 7 >= totalBytes) {
                                            logger.error("VaType=8：数据不足（需8字节）");
                                            break;
                                        }
                                        byte[] ulongBytes = {responseBytes[newOffset + 7], responseBytes[newOffset + 6],
                                                responseBytes[newOffset + 5], responseBytes[newOffset + 4],
                                                responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(ulongBytes).getLong(); // Java中long本身就是64位，无需特殊处理
                                        newOffset += 8;
                                        break;
                                    case 9: // double (8字节)
                                        if (newOffset + 7 >= totalBytes) {
                                            logger.error("VaType=9：数据不足（需8字节）");
                                            break;
                                        }
                                        byte[] doubleBytes = {responseBytes[newOffset + 7], responseBytes[newOffset + 6],
                                                responseBytes[newOffset + 5], responseBytes[newOffset + 4],
                                                responseBytes[newOffset + 3], responseBytes[newOffset + 2],
                                                responseBytes[newOffset + 1], responseBytes[newOffset]};
                                        value = ByteBuffer.wrap(doubleBytes).getDouble();
                                        newOffset += 8;
                                        break;
                                    default:
                                        logger.error("不支持的VaType：{}", vaType);
                                        break;
                                }
                            }

                            // 输出解析结果
                            logger.info("新SOE事件 --> 时间: {}, 名称字符串: {}, 事件类型: {}, 值类型: {}, 值: {}",
                                    newInstant, channelName, eventType, vaType, value);

                            // 构建SOE事件对象（使用Float类型存储值，需要根据实际需求调整）
                            float floatValue = 0.0f;
                            if (value instanceof Number) {
                                floatValue = ((Number) value).floatValue();
                            } else if (value instanceof Boolean) {
                                floatValue = ((Boolean) value) ? 1.0f : 0.0f;
                            }

                            SoeLs newSoeLs = SoeLs.builder()
                                    .unixTime1(utcSeconds)
                                    .unixTime2((int) utcMicroseconds)
                                    .channelName(channelName)
                                    .eventV(eventType)
                                    .val(floatValue)
                                    .build();

                            logger.info("新SOE事件对象: {}", newSoeLs);

                            // 检查是否已存在，不存在则插入数据库
                            if (!Dbsvr.isEntityExists(String.format("soe_s%spt", sysnum), "soe_ls", newSoeLs)) {
                                logger.info("新SOE实体不存在，准备添加");
                                if (Dbsvr.insertEntity(String.format("soe_s%spt", sysnum), "soe_ls", newSoeLs)) {
                                    logger.info("新SOE实体添加成功");
                                }
                            }

                            // 更新最新时间戳
                            SoeLastTime newSoeLastTimeNew = SoeLastTime.builder()
                                    .index(0)
                                    .unixTime1(utcSeconds)
                                    .unixTime2((int) utcMicroseconds)
                                    .build();
                            if (newSoeLastTimeNew.isNewer(newSoeLastTime1)) {
                                newSoeLastTime1 = newSoeLastTimeNew;
                            }
                        }
                    }
                    // 更新最新时间戳到数据库
                    if (newSoeLastTime1.isNewer(soeLastTime)) 
                    {
                        Dbsvr.updateEntity(String.format("soe_s%spt", sysnum), "last_time", "\"index\"", newSoeLastTime1);
                    }
                }
            //新soe报文解析末尾 
            }
            else{
                logger.info("SOE采集错误包已忽略");
            }
        } catch (SocketTimeoutException e) {
            logger.error("SOE采集连接服务器或读取数据超时", e);
        } catch (Exception e) {
            logger.error("SOE采集时发生异常S", e);
        } finally {
            // 确保资源被正确关闭
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();
                logger.debug("SOE采集连接已关闭");
            } catch (Exception e) {
                logger.error("SOE采集关闭连接时发生异常", e);
            }
        }
        return ret;
    }

    // 辅助方法：将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }
}